<?php 
namespace App\Services\User;

use Log;
use App\Facades\Infra\User\WeChatManage;

class WeChatService{
	
	public function subscribe($userInfo){
		
		$conditions['openid'] = $userInfo->openid;

		if(count(WeChatManage::getUserInfo($conditions)) == 0){
			WeChatManage::createUserInfo($this->constituteData($userInfo));
			return;
		}

		$data['subscribe'] = 1;

		WeChatManage::updateUserStatus($conditions,$data);

		return;
	}

	public function qRCodeSubcribe($userInfo,$formOpenid){

		$formOpenid = substr($formOpenid,8);

		$conditions['openid'] = $userInfo->openid;

		$data = $this->constituteData($userInfo);

		$data['form_openid'] = $formOpenid;

		if(count(WeChatManage::getUserInfo($conditions)) == 0){
			WeChatManage::createUserInfo($data);
			return;
		}

		$data['subscribe'] = 1;

		WeChatManage::updateUserStatus($conditions,$data);

		return;
	}

	public function unsubscribe($userInfo){

		$conditions['openid'] = $userInfo->openid;

		$data['subscribe'] = 0;

		WeChatManage::updateUserStatus($conditions,$data);

		return;
	}

	public function updateUserInfo($userInfo){
		
		$conditions['openid'] = $userInfo['openid'];

		$data = $this->constituteUpdataData($userInfo);

		if(count(WeChatManage::getUserInfo($conditions)) == 0){

			$data['subscribe'] = false;

			WeChatManage::createUserInfo($data);
			
			return;
		}

		WeChatManage::updateUserStatus($conditions,$data);

		return;
	}

	public function generateQRCode(){
		
		$wechat = app('wechat');

		$qrcode = $wechat->qrcode;

		$sceneValue = 'odh7zsgI75iT8FRh0fGlSojc9PWM';

		$result = $qrcode->forever($sceneValue);

		$ticket = $result->ticket;

		return $ticket;
	}

	public function constituteUpdataData($userInfo){

		$data = [
			'openid' => $userInfo['openid'],
			'nickname' => $userInfo['nickname'],
			'sex' => $userInfo['sex'],
			'city' => $userInfo['city'],
			'province' => $userInfo['province'],
			'headimgurl' => $userInfo['headimgurl'],
			'country' => $userInfo['country'],
		];

		return $data;
	}

	public function constituteData($userInfo){

		$data = [
			'openid' => $userInfo->openid,
			'nickname' => $userInfo->nickname,
			'sex' => $userInfo->sex,
			'city' => $userInfo->city,
			'province' => $userInfo->province,
			'remark' => $userInfo->remark,
			'groupid' => $userInfo->groupid,
			'headimgurl' => $userInfo->headimgurl,
			'country' => $userInfo->country
		];

		return $data;
	}
}